import express from "express";
import knex from "knex";
import shortid from "shortid";

const db = knex({
  client: "mysql2",
  connection: {
    host: "127.0.0.1",
    user: "debian-sys-maint",
    password: "0m20FnclbOfnDlfO",
    database: "short_link",
  },
});
const app = express();
app.use(express.json());

//接口创建短码并且关联url
app.post("/create_url", async (req, res) => {
  const short_id = shortid.generate();
  const url = req.body.url;
  await db("shorts").insert({
    short_id,
    url,
  });
  res.send(`http://127.0.0.1:3002/${short_id}`);
});
//将短码重定向到目标源地址
app.get("/:short_id", async (req, res) => {
  const short_id = req.params.short_id;
  const result = await db("shorts").select("url").where({ short_id });
  if (result && result[0]) {
    res.redirect(301, result[0].url);
  } else {
    res.sendStatus(404);
  }
});
app.listen(3002, () => {
  console.log("Server is running on port 3002");
});
